package com.itheima.chapter06.service;

import com.itheima.chapter06.domain.Comment;
import com.itheima.chapter06.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    public Comment findById(int commentId) {
        String keyName = getKeyName(commentId);
        Object object = redisTemplate.opsForValue().get(keyName);
        if (object != null) {
            return (Comment) object;
        }
        Optional<Comment> optional = commentRepository.findById(commentId);
        if (optional.isPresent()) {
            Comment comment = optional.get();
            redisTemplate.opsForValue().set(keyName, comment, 1, TimeUnit.DAYS);
            return comment;
        }
        return null;
    }

    private String getKeyName(int commentId) {
        String keyName = Comment.class.getCanonicalName() + "_" + commentId;
        return keyName;
    }

    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        String keyName = getKeyName(comment.getId());
        redisTemplate.opsForValue().set(keyName, comment);
        return comment;
    }

    public void deleteComment(int commentId) {
        commentRepository.deleteById(commentId);
        String keyName = getKeyName(commentId);
        redisTemplate.delete(keyName);
    }
}
